package cn.edu.ldu.communityqa.communityqa.controller;

import cn.edu.ldu.communityqa.communityqa.entity.Msg;
import cn.edu.ldu.communityqa.communityqa.entity.User;
import cn.edu.ldu.communityqa.communityqa.interceptor.ApiLoginInterceptor;
import cn.edu.ldu.communityqa.communityqa.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class LoginController {
    // 登录有效期 10 小时
    private final int EXPIRES_SECONDS = 60 * 60 * 10;
    private final UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse response
    ) {
        User user = userService.findByUsernameAndPassword(username, password);

        if (user == null) {
            return Msg.responseEntity("用户名或密码错误", HttpStatus.UNAUTHORIZED);
        }

        // 使用 ResponseCookie 构建第一个 Cookie (name)
        ResponseCookie nameCookie = ResponseCookie.from("username", user.getUsername())
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 使用 ResponseCookie 构建第二个 Cookie (password)
        ResponseCookie passwordCookie = ResponseCookie.from("password", user.getPassword())
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 使用 ResponseCookie 构建第二个 Cookie (role)
        ResponseCookie roleCookie = ResponseCookie.from("role", user.getRole())
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 添加 Cookie 到响应头
        response.setHeader(HttpHeaders.SET_COOKIE, nameCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, passwordCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, roleCookie.toString());

        return ResponseEntity.ok(user);
    }

    @GetMapping("/login")
    public ResponseEntity<Msg> setLogin(HttpServletResponse response) {

        // 使用 ResponseCookie 构建第一个 Cookie (name)
        ResponseCookie nameCookie = ResponseCookie.from("username", "xkk")
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 使用 ResponseCookie 构建第二个 Cookie (password)
        ResponseCookie passwordCookie = ResponseCookie.from("password", "123456")
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 使用 ResponseCookie 构建第二个 Cookie (role)
        ResponseCookie roleCookie = ResponseCookie.from("role", User.Role.ADMIN.name())
                .path("/")
                .maxAge(EXPIRES_SECONDS)
                .build();

        // 添加 Cookie 到响应头
        response.setHeader(HttpHeaders.SET_COOKIE, nameCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, passwordCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, roleCookie.toString());

        return Msg.responseEntity("登陆成功");
    }

    @GetMapping("/logout")
    public ResponseEntity<String> logout(HttpServletResponse response) {
        // 清除 "username" Cookie
        ResponseCookie nameCookie = ResponseCookie.from("username", "")
                .path("/")
                .maxAge(0L) // 立即过期
                .build();

        // 清除 "password" Cookie
        ResponseCookie passwordCookie = ResponseCookie.from("password", "")
                .path("/")
                .maxAge(0L) // 立即过期
                .build();

        // 清除 "role" Cookie
        ResponseCookie roleCookie = ResponseCookie.from("role", "")
                .path("/")
                .maxAge(0L) // 立即过期
                .build();

        // 添加清除的 Cookie 到响应头
        response.setHeader(HttpHeaders.SET_COOKIE, nameCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, passwordCookie.toString());
        response.addHeader(HttpHeaders.SET_COOKIE, roleCookie.toString());

        return ResponseEntity.ok("注销成功");
    }

    // 获取当前登录的用户信息
    @GetMapping("/user")
    public ResponseEntity<?> user(HttpServletRequest request) {
        String name = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (ApiLoginInterceptor.SESSION_COOKIE_USERNAME.equals(cookie.getName())) {
                    name = cookie.getValue();
                }
                if (ApiLoginInterceptor.SESSION_COOKIE_PASSWORD.equals(cookie.getName())) {
                    password = cookie.getValue();
                }
            }
        }

        if (name == null || password == null) {
            return Msg.responseEntity("未登录", HttpStatus.NOT_ACCEPTABLE);
        }
        User user = userService.findByUsernameAndPassword(name, password);
        if (user == null) {
            return Msg.responseEntity("无效账号", HttpStatus.UNAUTHORIZED);
        }

        return ResponseEntity.ok(user);
    }
}
